/*
 *  (c) 2010-2012 Ashwin Rayaprolu (http://linkwithweb.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
 *  file except in compliance with the License. You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software distributed under the
 *  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 *  either express or implied. See the License for the specific language governing permissions
 *  and limitations under the License.
 */
 

SwiftUI.UIPerspective = function(options) {
  this.initialize(options);
};

SwiftUI.UIPerspective.prototype = {
/**
 * @class Implements UI Perspective.. This class is tightly coupled with JQuery and Requires jquery
 * @constructs
 */
   initialize: function(options) {

      /**
       * Layout related.... stuff below
       */

      this.outerLayout = null
      this.innerLayout = null;
      /*
      *#######################
      * OUTER LAYOUT SETTINGS
      *#######################
      *
      * This configuration illustrates how extensively the layout can be customized
      * ALL SETTINGS ARE OPTIONAL - and there are more available than shown below
      *
      * These settings are set in 'sub-key format' - ALL data must be in a nested data-structures
      * All default settings (applied to all panes) go inside the defaults:{} key
      * Pane-specific settings go inside their keys: north:{}, south:{}, center:{}, etc
      */
      this.layoutSettings_Outer = {
      	name: "SwiftUILayout" // NO FUNCTIONAL USE, but could be used by custom code to 'identify' a layout
      	// options.defaults apply to ALL PANES - but overridden by pane-specific settings
      ,	defaults: {
      		size:					"auto"
      	,	minSize:				50
      	,	paneClass:				"pane" 		// default = 'ui-layout-pane'
      	,	resizerClass:			"resizer"	// default = 'ui-layout-resizer'
      	,	togglerClass:			"toggler"	// default = 'ui-layout-toggler'
      	,	buttonClass:			"button"	// default = 'ui-layout-button'
      	,	contentSelector:		".content"	// inner div to auto-size so only it scrolls, not the entire pane!
      	,	contentIgnoreSelector:	"span"		// 'paneSelector' for content to 'ignore' when measuring room for content
      	,	togglerLength_open:		35			// WIDTH of toggler on north/south edges - HEIGHT on east/west edges
      	,	togglerLength_closed:	35			// "100%" OR -1 = full height
      	,	hideTogglerOnSlide:		true		// hide the toggler when pane is 'slid open'
      	,	togglerTip_open:		"Close This Pane"
      	,	togglerTip_closed:		"Open This Pane"
      	,	resizerTip:				"Resize This Pane"
      	//	effect defaults - overridden on some panes
      	,	fxName:					"slide"		// none, slide, drop, scale
      	,	fxSpeed_open:			750
      	,	fxSpeed_close:			1500
      	,	fxSettings_open:		{ easing: "easeInQuint" }
      	,	fxSettings_close:		{ easing: "easeOutQuint" }
      }
      ,	north: {
      		size:					95
      	,	spacing_open:			1			// cosmetic spacing
      	,	togglerLength_open:		0			// HIDE the toggler button
      	,	togglerLength_closed:	-1			// "100%" OR -1 = full width of pane
      	,	resizable: 				false
      	,	slidable:				false
      	//	override default effect
      	,	fxName:					"none"
      	}
      ,	south: {
      		maxSize:				28
      	,	spacing_closed:			0			// HIDE resizer & toggler when 'closed'
      	,	slidable:				false		// REFERENCE - cannot slide if spacing_closed = 0
      	,	initClosed:				false
      	,   resizable: 				false
      	//	CALLBACK TESTING...
      	,	onhide_start:			function () {} //return confirm("START South pane hide \n\n onhide_start callback \n\n Allow pane to hide?"); }
      	,	onhide_end:				function () { } //alert("END South pane hide \n\n onhide_end callback"); }
      	,	onshow_start:			function () { } //return confirm("START South pane show \n\n onshow_start callback \n\n Allow pane to show?"); }
      	,	onshow_end:				function () { } //alert("END South pane show \n\n onshow_end callback"); }
      	,	onopen_start:			function () { } //return confirm("START South pane open \n\n onopen_start callback \n\n Allow pane to open?"); }
      	,	onopen_end:				function () { } //alert("END South pane open \n\n onopen_end callback"); }
      	,	onclose_start:			function () { } //return confirm("START South pane close \n\n onclose_start callback \n\n Allow pane to close?"); }
      	,	onclose_end:			function () { } //alert("END South pane close \n\n onclose_end callback"); }
      	,	onresize_start:			function () { } //return confirm("START South pane resize \n\n onresize_start callback \n\n Allow pane to be resized?)"); }
      	,	onresize_end:			function () { } //alert("END South pane resize \n\n onresize_end callback \n\n NOTE: onresize_start event was skipped."); }
      	}
      ,	west: {
      		size:					250
      	,   resizable: 				true	
      	,	spacing_closed:			21			// wider space when closed
      	,	togglerLength_closed:	21			// make toggler 'square' - 21x21
      	,	togglerAlign_closed:	"top"		// align to top of resizer
      	,	togglerLength_open:		0			// NONE - using custom togglers INSIDE west-pane
      	,	togglerTip_open:		"Close West Pane"
      	,   togglerContent_closed:  "M<br/>E<br/>N<br/>U"      		
      	,	togglerTip_closed:		"Open West Pane"
      	,	resizerTip_open:		"Resize West Pane"
      	,	slideTrigger_open:		"click" 	// default
      	,	initClosed:				false
      	//	add 'bounce' option to default 'slide' effect
      	,	fxSettings_open:		{ easing: "easeOutBounce" }
      	}
      ,	east: {
      		size:					350
      	,	spacing_closed:			21			// wider space when closed
      	,	togglerLength_closed:	21			// make toggler 'square' - 21x21
      	,	togglerAlign_closed:	"top"		// align to top of resizer
      	,	togglerLength_open:		0 			// NONE - using custom togglers INSIDE east-pane
      	,	togglerTip_open:		"Close East Pane"
      	,	togglerTip_closed:		"Open East Pane"
      	,	resizerTip_open:		"Resize East Pane"
      	,	slideTrigger_open:		"click"
      	,	resizable: 				true		
      	//,	slideTrigger_open:		"mouseover"	
      	,	initClosed:				false
      	//	override default effect, speed, and settings
      	,	fxName:					"drop"
      	,	fxSpeed:				"normal"
      	,	fxSettings:				{ easing: "" } // nullify default easing
      	}
      ,	center: {
      		paneSelector:			"#mainContent" 			// sample: use an ID to select pane instead of a class
      	,	onresize:				"innerLayout.resizeAll"	// resize INNER LAYOUT when center pane resizes
      	}
      };
      
      /**
       * Assign default data loading services url
       */
      this.options = {  
    	  leftTabs : ["services/menuController"],
      	  logWindowURL : "services/logController",
      	  rightTabs : ["services/rightPalletteController"],
      	  centerTabs : [],
      	  title : ""
      };
      
      this.leftTabHandle = null;
      this.rightTabHandle = null;
      this.centerTabHandle = null;
      
   
      SwiftUI.extend(this.options, options || {});
   },
   
   getTabHandles: function(){
	 return {left:this.leftTabHandle,center:this.centerTabHandle,right:this.rightTabHandle};  
   },
   
   setTitle: function(){
	   document.title = this.options.title;
	   $("#swiftui_header_title").empty();
	   $("#swiftui_header_title").append(this.options.title);
   },

   
   /**
    * Load tabs on left window..
    */
   loadLeftTabs : function(){
	   this.leftTabHandle =$('#swiftui_left_window_tabs').tabs({
	        add: function(e, ui) {
	            // append close thing
	            $(ui.tab).parents('li:first')
	                .append('<span class="ui-tabs-close ui-icon ui-icon-close" title="Close Tab"></span>')
	                .find('span.ui-tabs-close')
	                .click(function() {
	                	$('#swiftui_left_window_tabs').tabs('remove', $('li', $('#swiftui_left_window_tabs')).index($(this).parents('li:first')[0]));
	                });
	            // select just added tab
	            this.leftTabHandle.tabs('select', '#' + ui.panel.id);
	        }
	    });
	   
	   var index = 0;
	   for (var leftTab in this.options.leftTabs){
		   var st = "#swiftui_left_window_tab_"+index;
			if($(st).html() != null ) {
				this.leftTabHandle.tabs('select',st);
			} else {
				var url = leftTab;
				if (url != undefined && url != null) {
					if (url.indexOf("?") == -1) {
						url = url + "?1=1";
					} else {
						url = url + "&1=1";
					}
				}
				
				url = url +	"&mediUser="+ mediUser+"&mediPass="+mediEncryptedPassword
				
				this.leftTabHandle.tabs('add',st, index);
				$(st,"#tabs").load(url);
			}
		   
		   index = index + 1;
	   }
	   
   },
   
   
   /**
    * Load tabs on center window..
    */
   loadCenterTabs : function(){
	   var perspective = this;
	   this.centerTabHandle =$('#swiftui_center_window_tabs').tabs({
	        add: function(e, ui) {
	            // append close thing
	            $(ui.tab).parents('li:first')
	                .append('<span class="ui-tabs-close ui-icon ui-icon-close" title="Close Tab"></span>')
	                .find('span.ui-tabs-close')
	                .click(function() {
	                	$('#swiftui_center_window_tabs').tabs('remove', $('li', this).index($(this).parents('li:first')[0]));
	                });
	            // select just added tab
	            $('#swiftui_center_window_tabs').tabs('select', '#' + ui.panel.id);
	        }
	    });
	   
	   var index = 0;
	   for (var centerTab in this.options.centerTabs){
		   var st = "#swiftui_center_window_tab_"+index;
			if($(st).html() != null ) {
				this.centerTabHandle.tabs('select',st);
			} else {
				var url = centerTab;
				if (url != undefined && url != null) {
					if (url.indexOf("?") == -1) {
						url = url + "?1=1";
					} else {
						url = url + "&1=1";
					}
				}
				
				url = url +	"&mediUser="+ mediUser+"&mediPass="+mediEncryptedPassword
				
				this.centerTabHandle.tabs('add',st, index);
				$(st,"#tabs").load(url);
			}
		   
		   index = index + 1;
	   }
	   
	   this.centerTabHandle.bind('tabsselect', function(event, ui) {
		    // Objects available in the function context:
		    //ui.tab     // anchor element of the selected (clicked) tab
		    //ui.panel   // element, that contains the selected/clicked tab contents
		    //ui.index   // zero-based index of the selected (clicked) tab
	        try{
	        	try{
					ricoTables[ui.tab.hash.replace("#","")].resizeWindow();
				}catch(error){
				}
	    		$.validationEngine.closePrompt(".formError",true)
	        }catch(e){
	        }
		});
	   
   },
   
   /**
    * @param tabArea : left|center|right
    * @param tabIndex: unitId for tab
    * @param tabUrl  : URL that has to be loaded for that tab
    * Loads or selects any tab
    */
   loadOrSelectTab: function(tabArea,tabIndex,tabUrl){
	   var st = "#swiftui_"+tabArea+"_window_tab_"+tabIndex;
	   var tabHandle = SwiftUI.stringToObject(tabArea+"TabHandle",this);
	   
	    if($(st).html() != null ) {
	    	
	    	/**
			 * Reload rico grid if found
			 */
			try{
				ricoTables["customTab"+tabIndex].resizeWindow();
			}catch(error){
			}
			tabHandle.tabs('select',st);
		} else {
			var url = tabUrl;
			if (url != undefined && url != null) {
				if (url.indexOf("?") == -1) {
					url = url + "?1=1";
				} else {
					url = url + "&1=1";
				}
			}
			
			url = url +	"&mediUser="+ mediUser+"&mediPass="+mediEncryptedPassword
			
			tabHandle.tabs('add',st, tabIndex);
			
			SwiftUI.openProgressBar();
			$(st,"#swiftui_"+tabArea+"_window_tabs").load(url,function(){
				SwiftUI.closeProgressBar();
			});
		}
   },
   
   /**
    * Load tabs on right window..
    */
   loadRightTabs : function(){
	   this.rightTabHandle =$('#swiftui_right_window_tabs').tabs({
	        add: function(e, ui) {
	            // append close thing
	            $(ui.tab).parents('li:first')
	                .append('<span class="ui-tabs-close ui-icon ui-icon-close" title="Close Tab"></span>')
	                .find('span.ui-tabs-close')
	                .click(function() {
	                	$('#swiftui_right_window_tabs').tabs('remove', $('li', $('#swiftui_right_window_tabs')).index($(this).parents('li:first')[0]));
	                });
	            // select just added tab
	            this.rightTabHandle.tabs('select', '#' + ui.panel.id);
	        }
	    });
	   
	   var index = 0;
	   for (var rightTab in this.options.rightTabs){
		   var st = "#swiftui_right_window_tab_"+index;
			if($(st).html() != null ) {
				this.rightTabHandle.tabs('select',st);
			} else {
				var url = rightTab;
				if (url != undefined && url != null) {
					if (url.indexOf("?") == -1) {
						url = url + "?1=1";
					} else {
						url = url + "&1=1";
					}
				}
				
				url = url +	"&mediUser="+ mediUser+"&mediPass="+mediEncryptedPassword
				
				this.rightTabHandle.tabs('add',st, index);
				$(st,"#tabs").load(url);
			}
		   
		   index = index + 1;
	   }
   }
   
};

SwiftUI.includeLoaded('SwiftUIPerspective.js');